package com.example.easybuy.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

public class imageCode {

    private int aaa;

    private static String[] str = {"a", "b", "c", "d", "e", "f", "g", "h",
            "i", "j", "k", "m", "n", "p", "q", "r", "s", "t", "u",
            "v", "w", "x", "y", "z", "2", "3", "4", "5", "6", "7", "8", "9"};

    public static void main(String[] args) throws IOException {
        //定义图片的宽
        int w = 150;
        //定义图片的高
        int h = 50;
        //创建图片对象，RGB red green blue 红绿蓝 三原色
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        //获取画笔对象
        //Graphics g=image.getGraphics();

        //向下转型
        Graphics2D g = (Graphics2D) image.getGraphics();

        //把默认的图片修改成灰色的
        //给画笔设置颜色
        g.setColor(Color.green);
        g.fillRect(0, 0, w, h);

        //======================================
        //随机获取数据
        Random random = new Random();

        //设置画笔的颜色
        g.setColor(Color.red);
        //设置字体
        g.setFont(new Font("楷体", Font.BOLD, 38));

        //字符串在图片上的坐标
        int x = 30;
        int y = 30;

        //编写for循环
        for (int i = 0; i < 4; i++) {
            //随机获取数字
            int index = random.nextInt(str.length);
            //随机从数组中获取数据
            String strs = str[index];

            //随机生成角度-45 到 44
            int jd = random.nextInt(91) - 45;
            //弧度=角度*PI/180;
            double hd = jd * Math.PI / 180;

            //调用方法，设置字体的旋转
            g.rotate(hd, x, y);
            //随机获取一个数据，把该数据画到图片上去
            g.drawString(strs, x, y);
            //恢复回来
            g.rotate(-hd, x, y);
            //每次累加x的坐标
            x += 25;
        }

        //设置画笔颜色
        g.setColor(Color.yellow);
        //画几个线，循环几次
        int x1, x2, y1, y2;
        for (int i = 0; i < 10; i++) {
            x1 = random.nextInt(50);
            y1 = random.nextInt(h);

            x2 = random.nextInt(30) + 120;
            y2 = random.nextInt(h);
            g.drawLine(x1, y1, x2, y2);
        }
        //把内存中image对象保存到本地的磁盘上
        ImageIO.write(image, "jpg", new File("E:\\project\\eSuCai\\images\\imageCode\\aaa.jpg"));
    }
}
